<?php

namespace App\Http\Controllers\Operation;

use App\Http\Controllers\Controller;
use App\Http\Requests\Operation\ContentTemplateRequest;
use App\Jobs\Publish\ContentTemplateJob;
use App\Models\Common\CatData\Video\Vcat;
use App\Models\Common\CatData\Video\Vccat;
use App\Models\Common\CatData\Video\Vccattag;
use App\Models\Common\TagData\Video\Vcattag;
use App\Models\Entity\Column\Collist;
use App\Models\Operation\ContentTemplate;
use App\Models\Operation\ContentTemplateDetails;
use App\Models\Operation\ContentTemplateType;
// 2017/12/29 add
use App\Models\Operation\OperationTemplateData;
use App\Models\Operation\TemplateAreaData;
use App\Models\Publish\PublishContentTemplateHistory;
use App\Repositories\Operation\ContentTemplateRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;

class ContentTemplateController extends Controller
{
    use ModelForm;

    private $contentTemplateRepository;

    public function __construct(ContentTemplateRepository $contentTemplateRepo)
    {
        $this->contentTemplateRepository = $contentTemplateRepo;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // Admin::script('publishContentTemplate();');
        // Admin::script('publishOne();');

        return Admin::content(function (Content $content) use ($request) {

            $content->header(__('operation.content_templates.index_header'));
            $content->description(__('operation.content_templates.index_description'));

            $content->body($this->grid($request));
        });
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('operation.content_templates.create_header'));
            $content->description(__('operation.content_templates.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ContentTemplateRequest $request)
    {
        $input = $request->all();

        $contentTemplate = $this->contentTemplateRepository->create($input);

        Flash::success(__('operation.content_templates.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('operation.content_templates.index'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $contentTemplate = $this->contentTemplateRepository->findWithoutFail($id);

        if (empty($contentTemplate)) {
            Flash::error(__('operation.content_templates.not_found'));

            return redirect(route('operation.content_templates.index'));
        }

        return view('operation.content_templates.show')->with('contentTemplate', $contentTemplate);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('operation.content_templates.edit_header'));
            $content->description(__('operation.content_templates.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ContentTemplateRequest $request, $id)
    {
        $contentTemplate = $this->contentTemplateRepository->findWithoutFail($id);

        if (empty($contentTemplate)) {
            Flash::error(__('operation.content_templates.not_found'));

            return redirect(route('operation.content_templates.index'));
        }

        $input = $request->all();

        $contentTemplate = $this->contentTemplateRepository->update($input, $id);

        Flash::success(__('operation.content_templates.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('operation.content_templates.index'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->contentTemplateRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('operation.content_templates.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $contentTemplate = $this->contentTemplateRepository->findWithoutFail($id);

        if (empty($contentTemplate)) {
            Flash::error(__('operation.content_templates.not_found'));

            return redirect(route('operation.content_templates.index'));
        }

        if ($flag = $this->contentTemplateRepository->delete($id)) {
            return response()->json(['message' => __('operation.content_templates.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form 表单]
     * @return [type] [description]
     */
    protected function form()
    {
        return Admin::form(ContentTemplate::class, function (Form $form) {
            // ID
            $form->display('id', 'ID');
            // 内容模板编号
            $form->display('template_no', '内容模板编号')->help('必填');
            // 内容模板名称
            $form->text('name', '内容模板名称')->help('必填');
            // 模板别名
            $form->text('alias', '模板别名')->help('必填');
            // 模板类型
            $contentTemplateTypes = ContentTemplateType::orderBy('listorder', 'asc')->pluck('alias', 'id');
            $form->select('content_template_type_id', '内容模板类型')->options($contentTemplateTypes);
            // 描述
            $form->textarea('description', '描述');
            // 排序
            $form->number('listorder', '排序')->default(0);

            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));
        });
    }

    /**
     * [grid 表格]
     * @return [type] [description]
     */
    protected function grid(Request $request)
    {
        return Admin::grid(ContentTemplate::class, function (Grid $grid) use ($request) {
            // 范围查询 , 判断是否传递模板风格ID
            if (!empty($request->get('template_type_id'))) {
                $grid->model()->where(['template_style_id' => $request->get('template_type_id')])->orderBy('created_at', 'desc');
            } else {
                $grid->model()->orderBy('created_at', 'desc');
            }

            // 添加按钮
            if (!\Gate::check('operation.content_templates.create')) {
                // 禁用添加按钮
                $grid->disableCreation();
            }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     //编辑按钮
            //     if (!\Gate::check('operation.content_templates.edit')) {
            //         $actions->disableEdit();
            //     }
            //     //删除按钮
            //     if (!\Gate::check('operation.content_templates.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // //导出按钮
            // if (!\Gate::check('operation.content_templates.export')) {
            //     $grid->disableExport();
            // }

            // //批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         //批量删除按钮
            //         if (!\Gate::check('operation.content_templates.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 表格中的按钮
            $grid->actions(function ($actions) {
                // ' . route($route_prefix . '.user.distributionView', $actions->getKey()) . '
                $id = $actions->getKey();
                // 编辑按钮
                // $actions->disableEdit();
                // 删除按钮
                $actions->disableDelete();
                $templateStyleId = $actions->row->template_style_id;
                $templateType    = 'template-' . $templateStyleId;
                // 获取当前行的内容编号
                $templateNo = $actions->row->template_no;
                $actions->prepend('<a href="' . route('operation.content_templates.data_create', ['template_type' => $templateType, 'template_no' => $templateNo]) . '" title="查看模板样式"><i class="fa fa-list"></i></a>');
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('template_no', '内容模板编号')->sortable();
            $grid->column('name', '内容模板名称')->sortable();
            $grid->column('alias', '模板别名')->sortable();
            $grid->column('contentTemplateType.alias', '内容模板类型')->sortable();
            $grid->column('templateStyle.name', '模板风格')->sortable();
            $grid->column('listorder', '排序')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                $filter->disableIdFilter();
                // 编号
                $filter->like('template_no', '模板编号');
                // 名称
                $filter->like('name', '模板名称');
                // 模板别名
                $filter->like('alias', '模板别名');
                // 模板类型
                $contentTemplateTypes = ContentTemplateType::orderBy('listorder', 'asc')->pluck('alias', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('contentTemplateType', function ($query) use ($input) {
                        $query->where('id', '=', "{$input}");
                    });

                }, '模板类型')->select($contentTemplateTypes);
            });
        });
    }

    /**
     * [area 区位模板]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function template(Request $request)
    {
        // dd($request->route('template_type'));
        // dd($request->route('template_no'));
        // strtolower
        // http://[host]:[port]/data/AREA/001/{datetime}/{spid}/{chanid}/{term}/{midware}/
        // return view('operation/templates/area/template1');
    }

    /**
     * 数据列表
     */
    public function dataList(Request $request)
    {
        $templateType = $request->route('template_type');
        $templateNo   = $request->route('template_no');

        return Admin::content(function (Content $content) use ($templateType, $templateNo) {

            // $content->header(__('operation.content_templates.index_header'));
            // $content->description(__('operation.content_templates.index_description'));

            $content->body($this->dataListGrid($templateType, $templateNo));
        });
    }

    /**
     * 模板数据新建视图
     */
    public function dataCreate(Request $request)
    {
        // \View::addExtension('html', 'php');
        // return view('index'); //返回index.html文件
        $templateType = strtolower($request->route('template_type'));
        $templateNo   = $request->route('template_no');

        $templateDetailsId = $request->input('templateDetailsId');
        // 模板的ID
        $content_template_id = $request->input('content_template_id');
        // 媒资归类
        $vcats = Vcat::get(['name', 'id']);
        // 媒资分类数据
        $vcattags = Vcattag::get(['name', 'id']);
        // 栏目列表数据
        $collists = Collist::get(['name', 'id']);
        // 直播分类数据
        $vccattags = Vccattag::get(['name', 'id']);
        // 直播归类数据
        $vccats = Vccat::get(['name', 'id']);
        // 当前模板绑定的栏目名称
        $contentTemplate = ContentTemplate::with('cols')->where('id', $content_template_id)->first();
        if (empty($contentTemplate)) {
            $columnName = null;
        } else {
            if (count($contentTemplate->cols)) {
                // 栏目名称
                $columnName = $contentTemplate->cols->title;
            } else {
                $columnName = null;
            }
        }

        return view('operation/templates/' . $templateType . '/' . $templateNo, ['vcats' => $vcats, 'vcattags' => $vcattags, 'vccattags' => $vccattags, 'vccats' => $vccats, 'collists' => $collists, 'templateDetailsId' => $templateDetailsId, 'columnName' => $columnName]);
    }

    /**
     * [grid 表格]
     * @return [type] [description]
     */
    protected function dataListGrid($templateType, $templateNo)
    {
        return Admin::grid(OperationTemplateData::class, function (Grid $grid) use ($templateType, $templateNo) {
            $grid->model()->where(['template_type' => $templateType, 'template_no' => $templateNo]);

            $grid->column('template_type', '内容模板类型')->sortable();
            $grid->column('template_no', '内容模板编号')->sortable();
            $grid->column('sp_id', '服务商')->sortable();
            $grid->column('channel_id', '频道')->sortable();
            $grid->column('terminal', '终端')->sortable();
            $grid->column('middleware', '中间件')->sortable();
            $grid->column('content', '内容')->sortable();
            $grid->column('start_time', '开始时间')->sortable();
            $grid->column('end_time', '结束时间')->sortable();
            // /**
            //  * 过滤处理
            //  */
            // $grid->filter(function ($filter) {
            //     // 禁用id查询框
            //     $filter->disableIdFilter();
            //     // 编号
            //     $filter->like('template_no', '模板编号');
            //     // 名称
            //     $filter->like('name', '模板名称');
            //     // 模板别名
            //     $filter->like('alias', '模板别名');
            //     // 模板类型
            //     $contentTemplateTypes = ContentTemplateType::orderBy('listorder', 'asc')->pluck('alias', 'id');
            //     $filter->where(function ($query) {
            //         $input = $this->input;
            //         $query->whereHas('contentTemplateType', function ($query) use ($input) {
            //             $query->where('id', '=', "{$input}");
            //         });

            //     }, '模板类型')->select($contentTemplateTypes);
            // });
        });
    }

}
